#include <string.h>
#include <stdio.h>
#include "wavehdr.h"

void wavehdr_init(WaveHeader* header)
{
	if (header)
	{
		memcpy(header->riff_id, "RIFF", 4);
		memcpy(header->riff_type, "WAVE", 4);
		memcpy(header->fmt_id, "fmt ", 4);
		header->fmt_datasize = 16;
		header->fmt_compression_code = 1;
		memcpy(header->data_id, "data", 4);
	}
}

void wavehdr_set_fmt(WaveHeader* header, int channels, int sampleRate,
		int bytesPerSample)
{
	if (header)
	{
		header->fmt_channels = channels;
		header->fmt_sample_rate = sampleRate;
		header->fmt_block_align = channels * bytesPerSample;
		header->fmt_avg_bytes_per_sec = header->fmt_block_align * sampleRate;
		header->fmt_bit_per_sample = bytesPerSample << 3;
	}
}

void wavehdr_set_size(WaveHeader* header, int rawDataSize)
{
	if (header)
	{
		header->riff_datasize = rawDataSize + sizeof(WaveHeader) - 8;
		header->data_datasize = rawDataSize;
	}
}


void wavehdr_print(WaveHeader* header)
{
	printf("channels:\t%d\n", header->fmt_channels);
	printf("avg_bytes_per_sec:\t%d\n", header->fmt_avg_bytes_per_sec);
	printf("block align:\t%d\n", header->fmt_block_align);
	printf("sample rate:\t%d\n", header->fmt_sample_rate);
	printf("audio data size:\t%d\n", header->data_datasize);
	printf("fmt data size:\t%d\n",header->fmt_datasize);
}

void wave_write_file(char *fn,int rate,char *data,int bytes)
{
	WaveHeader hdr;
	FILE *f;

	wavehdr_init(&hdr);
	wavehdr_set_fmt(&hdr,1,rate,2);
	wavehdr_set_size(&hdr,bytes);
	f=fopen(fn,"wb");
	fwrite((void*)&hdr,1,sizeof(hdr),f);
	fwrite((void*)data,1,bytes,f);
	fclose(f);
}
